/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.orderoid.ejb.facade;

import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.orderoid.ejb.domain.Menu;

/**
 *
 * @author Dahlia
 */
@Stateless
public class MenuFacade extends AbstractFacade<Menu> {
    @PersistenceContext(unitName = "Orderoid-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public MenuFacade() {
        super(Menu.class);
    }
    
    public void desactiver(Menu menu){
        menu.setDateFin(new Date());
        edit(menu);
    }
    
    public List<Menu> findAllActif(Integer idRestaurant){
        String req = "SELECT p FROM Menu p "
                + " JOIN p.restaurantCollection r"
                + " WHERE p.dateFin is null "
                + " AND r.idRestaurant IN (:idResto)";
        Query query = em.createQuery(req);
        query.setParameter("idResto", idRestaurant);
        return query.getResultList();
    }
    
    public List<Menu> findRangeActif(int[] range, Integer idRestaurant){
        
        String req = "SELECT p FROM Menu p "
                + " JOIN p.restaurantCollection r"
                + " WHERE p.dateFin is null "
                + " AND r.idRestaurant IN (:idResto)";
        Query query = em.createQuery(req);
        query.setParameter("idResto", idRestaurant);
        query.setMaxResults(range[1] - range[0]);
        query.setFirstResult(range[0]);
        return query.getResultList();
    }
    
    public void modifier(Menu menu){
        
        //désactivation de l'ancien menu
        Menu menuEnBase = find(menu.getIdMenu());
        desactiver(menuEnBase);
        
        //création d'un nouveau menu
        menu.setIdMenu(null);
        create(menu);
    }
    
    public int countActif(Integer idRestaurant){
        String req = "SELECT count(m) FROM Menu m "
                + " JOIN m.restaurantCollection r"
                + " WHERE m.dateFin is null "
                + " AND r.idRestaurant IN (:idResto)";
        Query query = em.createQuery(req);
        query.setParameter("idResto", idRestaurant);
        return ((Long) query.getSingleResult()).intValue();
    }
}
